package com.wzdigit.wms.wms.service.core;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wzdigit.framework.Shift;
import com.wzdigit.mes.basic.api.BasicDataItemDetailApi;
import com.wzdigit.mes.basic.api.BasicSimpleCodeRuleApi;
import com.wzdigit.mes.basic.dto.DataItemDetailDTO;
import com.wzdigit.wms.basic.domain.dtos.inventory.UpdateInventoryInputDto;
import com.wzdigit.wms.basic.domain.dtos.oqc.OqcInspDtlDto;
import com.wzdigit.wms.basic.domain.inventory.Goods;
import com.wzdigit.wms.basic.domain.inventory.GoodsHis;
import com.wzdigit.wms.basic.domain.inventory.GoodsLog;
import com.wzdigit.wms.basic.domain.inventory.GoodsVersion;
import com.wzdigit.wms.basic.domain.oqc.OqcInsp;
import com.wzdigit.wms.basic.domain.order.TrsnDtl;
import com.wzdigit.wms.basic.domain.order.TrsnDtlGoods;
import com.wzdigit.wms.basic.domain.order.TrsnHeader;
import com.wzdigit.wms.basic.domain.transfer.GdnDtl;
import com.wzdigit.wms.basic.domain.transfer.GdnDtlGoods;
import com.wzdigit.wms.basic.domain.transfer.GdnHeader;
import com.wzdigit.wms.basic.enums.*;
import com.wzdigit.wms.basic.mapper.core.inventory.GoodsHisMapper;
import com.wzdigit.wms.basic.mapper.core.inventory.GoodsLogMapper;
import com.wzdigit.wms.basic.mapper.core.inventory.GoodsMapper;
import com.wzdigit.wms.basic.mapper.core.oqc.OqcInspMapper;
import com.wzdigit.wms.basic.mapper.core.order.TrsnDtlGoodsMapper;
import com.wzdigit.wms.basic.mapper.core.order.TrsnDtlMapper;
import com.wzdigit.wms.basic.mapper.core.order.TrsnHeaderMapper;
import com.wzdigit.wms.basic.mapper.core.transfer.GdnDtlGoodsMapper;
import com.wzdigit.wms.basic.mapper.core.transfer.GdnDtlMapper;
import com.wzdigit.wms.basic.mapper.core.transfer.GdnHeaderMapper;
import com.wzdigit.wms.basic.service.code.InventoryService;
import com.wzdigit.wms.basic.service.code.LotnoService;
import com.wzdigit.wms.basic.util.HttpSessionUtil;
import com.wzdigit.wms.wms.service.order.TrsnService;
import com.wzdigit.wms.wms.service.wms2sap.ReportCheckService;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.core.utils.BeanUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 
 * 翻拍-判检执行【判检单主档分组（工厂、仓库）处理】
 * @author Administrator
 *
 */
@Service
@Slf4j
public class OqcGroupNewTaskService {
	private static final String OQC_GDN="oqc_gdn";
	private static final String GDN_D98="GDN_D98";
	private static final String TRSN_ORDER = "TRSN_ORDER";

	@Value(value = "${default_owner.code}")
	private String DEFAULT_OWNER;
	@Value(value = "${default_owner.name}")
	private String DEFAULT_OWNER_NAME;

	@Autowired
	private OqcInspMapper oqcInspMapper;
	@Autowired
	private GdnHeaderMapper gdnHeaderMapper;
	@Autowired
	private GdnDtlMapper gdnDtlMapper;
	@Autowired
	private GdnDtlGoodsMapper gdnDtlGoodsMapper;
	@Autowired
	private GoodsLogMapper goodsLogMapper;
	@Autowired
	private GoodsHisMapper goodsHisMapper;
	@Autowired
	private GoodsMapper goodsMapper;
	@Autowired
	private TrsnHeaderMapper trsnHeaderMapper;
	@Autowired
	private TrsnDtlMapper trsnDtlMapper;
	@Autowired
	private TrsnDtlGoodsMapper trsnDtlGoodsMapper;

	@Autowired
	private OqcInspServcie oqcInspServcie;
	@Autowired
    private OqcDtlNewTaskService oqcDtlNewTaskService;
	@Autowired
    private ReportCheckService reportCheckService;
	@Autowired
	private InventoryService inventoryService;
	@Autowired
	private TrsnService trsnService;

	@Reference(version = "${dubbo.consumers.basic.data.item.detail.api:1.0.0}", check = false, timeout = 300000)
	private BasicDataItemDetailApi dataItemDetailApi;
	@Reference(version = "${dubbo.consumers.basic.simple.code.rule.api:1.0.0}", check = false)
	private BasicSimpleCodeRuleApi basicSimpleCodeRuleApi;
	
	/**
	 * 判检单主档分组执行入口
	 * 
	 * @param oqcInsp				送检单主档实体
	 * @param oqcInspDtlList		送检单明细组别集合【工厂、仓库】分组
	 * @param isCallSAPInterface	是否回传SAP标识
	 * @return
	 * @throws Exception
	 */
	@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
	public List<GoodsVersion> execute(OqcInsp oqcInsp, List<OqcInspDtlDto> oqcInspDtlList, boolean isCallSAPInterface) throws Exception {
		int groupDealOkSize = 0;
		List<GoodsVersion> goodsVersionList=new ArrayList<>();
    	// 遍历送检单明细
        for (OqcInspDtlDto oqcInspDtl : oqcInspDtlList) {
        	try {
				GoodsVersion goodsVersion = oqcDtlNewTaskService.execute(oqcInsp.getInspResult(), oqcInspDtl);
				groupDealOkSize++;
				goodsVersionList.add(goodsVersion);
        		log.info("【定时任务-产品判检】明细执行成功：{}", oqcInspDtl.getOqcInspDtlId());
			} catch (Exception e) {
				log.error("【定时任务-产品判检】明细执行异常/失败：{}", oqcInspDtl.getOqcInspDtlId());
				e.printStackTrace();
			}
        } // 明细循环处理结束
        
        
        // 当前组别处理成功数量大于0才更新送检单状态和回传sap
        if(groupDealOkSize > 0) {
        	// 是否需要更新QMS状态
        	boolean isCallQms = true;
        	
        	// 当前明细的未处理的数量
        	int totalNoDealDtlSize = oqcInspServcie.selectTotalNoDealDtlSizeByOqcInspId(oqcInsp.getOqcInspId());
        	if (totalNoDealDtlSize == 0) {
        		// 全部处理
        		oqcInspMapper.updateStatusById(oqcInsp.getOqcInspId(), OqcInspStatusEnum.OQC_STATUS_AFTER_HANDLE.getCode());
        	} else {
        		// 部分处理
        		oqcInspMapper.updateStatusById(oqcInsp.getOqcInspId(), OqcInspStatusEnum.OQC_STATUS_PART_HANDLE.getCode());
        		isCallQms = false;
        	}

			//TODO ZYF:如果是散件/内销自动生产
			/*if (goodsVersionList.size()>0){
				try {
					autoGdn(goodsVersionList,oqcInsp);
				}catch (Exception e){
					log.info("自动出库失败!");
					e.printStackTrace();
				}
			}*/

        	// 调QMS向SAP报检接口
        	if (isCallSAPInterface) {
        		String factory = oqcInspDtlList.get(0).getFactory();
        		String whsCode = oqcInspDtlList.get(0).getWhsCode();
        		Boolean result = reportCheckService.reportAndUpdateSchedule(oqcInsp, factory, whsCode, groupDealOkSize, isCallQms);
        		if (!result) {
					throw new Exception("回传SAP判检失败");
				}
        	}

        	return goodsVersionList;
        } else {
        	throw new Exception("当前主档分组判检成功的数量为0");
        }
    }





}
